﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Perceiveit.Xml.Converters
{
    public class ImageXConverter : XConverter<System.Drawing.Image>
    {
        public override System.Drawing.Image FromString(string value)
        {
            System.Drawing.Image img = null;

            if (!string.IsNullOrEmpty(value))
            {
                System.IO.MemoryStream ms = null;
                try
                {
                    byte[] data = Convert.FromBase64String(value);
                    ms = new System.IO.MemoryStream(data);

                    img = System.Drawing.Image.FromStream(ms);
                }
                catch (FormatException)
                {
                    if (img != null)
                        img.Dispose();
                    if (ms != null)
                        ms.Dispose();
                    img = null;
                }
                catch (ArgumentException)
                {
                    if (img != null)
                        img.Dispose();
                    if (ms != null)
                        ms.Dispose();
                    img = null;
                }
            }

            return img;
                
        }


        public override string ToString(System.Drawing.Image value)
        {
            if (null == value)
            {
                return string.Empty;
            }
            else
            {
                byte[] data = null;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                try
                {
                    value.Save(ms, value.RawFormat);
                    data = ms.ToArray();
                }
                catch (ArgumentNullException)
                {
                }
                catch (System.Runtime.InteropServices.ExternalException)
                {
                }
                finally
                {
                    ms.Dispose();
                }

                if (null == data || data.Length == 0)
                    return string.Empty;
                else
                    return Convert.ToBase64String(data, Base64FormattingOptions.InsertLineBreaks);

            }
        }
    }
}
